package com.victor.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

public class FileUpload {

	public static String uploadFile(MultipartFile multipartFile, HttpServletRequest request) throws Exception {
		// 获取的是用户提交的文件名字
		String originalFilename = multipartFile.getOriginalFilename();
		// 开始将用户上传的文件保存到对应的盘符中去
		String randomUUID = UUID.randomUUID().toString();
		// 通过originalFilename来获取文件的后缀名
		String exet = originalFilename.substring(originalFilename.lastIndexOf("."));
		//  根据当前的系统时间生成对应的文件夹 ：格式为yyyyMMdd
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String dateStr = sdf.format(date);

		String filePath = request.getSession().getServletContext().getRealPath("/fileUpload/" + dateStr + "/");
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		filePath += "\\" + randomUUID + exet;
		multipartFile.transferTo(new File(filePath));
		return "fileUpload/" + dateStr + "/" + randomUUID + exet;
	}

	// 删除图片
	public static void deleteFile(String oldPath, HttpServletRequest request) throws Exception {
		String path = request.getSession().getServletContext().getRealPath("/fileUpload");
		try {
			int i = (oldPath.indexOf("/"));
			String imgPath = oldPath.substring(i);
			String getPath = path + "\\" + imgPath;
			File dir = new File(getPath);
			dir.delete();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static void download(HttpServletRequest request, HttpServletResponse response, String path) throws ServletException, IOException {
		String newpath = request.getServletContext().getRealPath("") + path;
		File file = new File(newpath);
		if (!file.exists()) {
			request.setAttribute("message", "您要下载的资源已被删除！！");
			return;
		}
		String realname = path.substring(path.lastIndexOf("/") + 1);
		response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
		// 读取要下载的文件，保存到文件输入流
		FileInputStream fis = new FileInputStream(newpath);
		// 创建输出流
		OutputStream fos = response.getOutputStream();
		// 设置缓存区
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		// 输入通道
		FileChannel readChannel = fis.getChannel();
		// 输出通道
		// FileChannel writeChannel = fos.write(b);
		while (true) {
			buffer.clear();
			int len = readChannel.read(buffer);// 读入数据
			if (len < 0) {
				break;// 传输结束
			}
			buffer.flip();
			fos.write(buffer.array());// 写入数据
		}
		// 关闭输入流
		fis.close();
		// 关闭输出流
		fos.close();
	}

	public static void download(HttpServletRequest request, OutputStream fos, String path) throws IOException {
		String newpath = request.getServletContext().getRealPath("") + path;
		File file = new File(newpath);
		if (!file.exists()) {
			request.setAttribute("message", "您要下载的资源已被删除！！");
			return;
		}
		// 读取要下载的文件，保存到文件输入流
		FileInputStream fis = new FileInputStream(newpath);
		// 创建输出流
		// 设置缓存区
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		// 输入通道
		FileChannel readChannel = fis.getChannel();
		// 输出通道
		// FileChannel writeChannel = fos.write(b);
		while (true) {
			buffer.clear();
			int len = readChannel.read(buffer);// 读入数据
			if (len < 0) {
				break;// 传输结束
			}
			buffer.flip();
			fos.write(buffer.array());// 写入数据
		}
		// 关闭输入流
		fis.close();
	}

}
